﻿
using System;
using System.Reflection;
using SType = System.Type;

namespace UFrame
{



    public class Singleton<T> where T : class
    {
        private static T instance = null;

        public static T I
        {
            get
            {
                if (null == instance)
                {
                    SType type = typeof(T);
                    if (type.IsAbstract || type.IsInterface)
                    {
                        throw (new Exception("Class type must could be instantiated. Don't use abstract or interface"));
                    }

                    ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,
                                                                        null,
                                                                        SType.EmptyTypes,
                                                                        null);
                    if (null == constructor)
                    {
                        throw (new Exception("Constructor must empty"));
                    }
                    if (!constructor.IsPrivate)
                    {
                        throw (new Exception("Constructor must be a private function"));
                    }
                    instance = constructor.Invoke(null) as T;
                }
                return instance;
            }
            set
            {
                instance = value;
            }
        }

        public void Destroy()
        {
            instance = null;
        }
    }
}